'''
利用paramiko模块对linux服务器进行远程操作
'''

from core.Setting import server_mongo,server_redis,server_web
import paramiko


class Linux:

    IP=None
    PORT=None
    USER=None
    PWD=None

    def __init__(self,ip,port,usr,pwd):

        Linux.IP=ip
        Linux.PORT=port
        Linux.USER=usr
        Linux.PWD=pwd

    def connect(self):
        '''建立连接'''
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(Linux.IP, Linux.PORT, Linux.USER, Linux.PWD, timeout=10)

        return client


script_web = '/monitor/script_web.py'
script_mongo = '/monitor/script_mongo.py'
script_redis = '/monitor/script_redis.py'

linux_web = Linux(server_web['host'],
                  server_web['port'],
                  server_web['user'],
                  server_web['password']).connect()       # web服务器

linux_mongo = Linux(server_mongo['host'],
                    server_mongo['port'],
                    server_mongo['user'],
                    server_mongo['password']).connect()     # mongo服务器

linux_redis = Linux(server_redis['host'],
                    server_redis['port'],
                    server_redis['user'],
                    server_redis['password']).connect()     # redis服务器

def open_monitor():
    '''
    启动压测环境，web服务器、mongo服务器、redis服务器上的系统资源监控
    nohup ./python3.6 /monitor/script.py   启动脚本命令(终端连接脚本仍然运行)
    '''
    linux_web.exec_command('cd /\n' +
                       'cd /usr/local/python3.6.6/bin\n' +
                       'nohup ./python3.6 {}\n'.format(script_web))

    linux_mongo.exec_command('cd /\n' +
                           'cd /usr/local/python3.6.6/bin\n' +
                           'nohup ./python3.6 {}\n'.format(script_mongo))

    linux_redis.exec_command('cd /\n' +
                           'cd /usr/local/python3.6.6/bin\n' +
                           'nohup ./python3.6 {}\n'.format(script_redis))

def close_monitor():
    '''
    ps -ef |grep /monitor/script.py | grep -v grep | awk '{print $2}'    查询所有关于"/monitor/script.py"的进程
    kill -s 9 PID    关闭指定进程
    '''
    stdin,stdout,stderr=linux_web.exec_command("ps -ef |grep %s | grep -v grep | awk '{print $2}'" % script_web)  # 查看进程
    PID_web=[i.replace('\n','') for i in stdout.readlines()]
    for i in PID_web:
        linux_web.exec_command("kill -s 9 {}".format(i))


    stdin,stdout,stderr=linux_mongo.exec_command("ps -ef |grep %s | grep -v grep | awk '{print $2}'" % script_mongo)  # 查看进程
    PID_mongo=[i.replace('\n','') for i in stdout.readlines()]
    for i in PID_mongo:
        linux_mongo.exec_command("kill -s 9 {}".format(i))


    stdin,stdout,stderr=linux_redis.exec_command("ps -ef |grep %s | grep -v grep | awk '{print $2}'" % script_redis)  # 查看进程
    PID_redis=[i.replace('\n','') for i in stdout.readlines()]
    for i in PID_redis:
        linux_redis.exec_command("kill -s 9 {}".format(i))



if __name__ == '__main__':
    # open_monitor()
    close_monitor()
